<template>
  <el-dialog
    v-model="dialogVisible"
    :title="ruleForm.id ? '修改品牌' : '新增品牌'"
    width="430"
    class="qc-custom-dialog"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="110px"
      class="dialog-form-wrap"
    >
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model.trim="ruleForm.brandName"
          placeholder="请输入品牌名称"
          maxlength="30"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="hide">取消</el-button>
        <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="dialog-brand">
import type { FormInstance, FormRules } from 'element-plus';
import { addEquipmentBrand, updateEquipmentBrand } from '@/service/apis/config';

const emit = defineEmits(['getData', 'clear-cache']);

const ruleFormRef = ref<FormInstance>();

let dialogVisible = ref(false);

let ruleForm = reactive({
  id: '',
  brandName: '',
});

const rules = reactive<FormRules>({
  brandName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    // { validator: checkNumber, trigger: ['blur', 'change'] },
  ],
});

// 显示弹框
const show = (row: any) => {
  dialogVisible.value = true;
  ruleForm.id = row.id;
  if (!ruleForm.id) {
    ruleForm.brandName = '';
  } else {
    ruleForm.brandName = row.brandName;
  }
  ruleFormRef.value?.clearValidate();
};
// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};

const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('submit---', ruleForm);
      if (ruleForm.id) {
        updateEquipmentBrand(ruleForm).then((res: any) => {
          hide();
          emit('clear-cache');
          emit('getData');
        });
      } else {
        addEquipmentBrand(ruleForm).then((res: any) => {
          hide();
          emit('clear-cache');
          emit('getData');
        });
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

defineExpose({
  show,
});
</script>